import 'package:aweb5/Constants.dart';
import 'package:aweb5/pages/AplusLoginWithPhone.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/FileUtil.dart';
import 'package:aweb5/util/HttpUtils1.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/fluwxUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:fluwx/fluwx.dart';
import 'package:load/load.dart';
import 'package:aweb5/Constants.dart';
import 'package:aweb5/bean/aplus/phone_code_entity.dart';
import 'package:aweb5/generated/json/member_info_entity_helper.dart';
import 'package:aweb5/generated/json/phone_code_entity_helper.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:aweb5/widgetlib/LoginFormCode.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/StringUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/bean/aplus/member_info_entity.dart';
import 'package:aweb5/util/SharedUtil.dart';
import 'package:aweb5/util/DateUtil.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:aweb5/util/PermissionUtil.dart';
import 'Agreement1.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget {
  bool show;
  LoginPage(this.show);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String _result = "无";
  String code = "";
  bool checked = false;
  BuildContext context;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();


   if(widget.show){
     WidgetsBinding.instance.addPostFrameCallback((Duration duration) {
       print(">>>post");

//        if(v==null){



       DialogUtil.showdialog(
           context,
           WillPopScope(child:
           Column(
             children: <Widget>[
               Text("个人信息保护指引",style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),
               Expanded(child: SingleChildScrollView(
                 child: Html(
                   data: """
    <!--For a much more extensive example, look at example/main.dart-->
     
    <p>1. 在浏览使用时，我们会使用您的设备标识信息用于推荐。</p>
<p>2. 我们可能会使用您的位置信息，为您推荐附近的服务，但不会收集和存储任何精确位置信息。</p>
<p>3. 您可以查看完整版<a href="https://h5.hhnry.com/agreement.html">《用户协议》</a>和<a href="https://h5.hhnry.com/agreement1.html">《隐私政策》</a>以便了解我们使用您手机信息的情况，以及对信息的保护措施。</p>
<br>
<br>
    <p>如果您同意请点击下面的按钮以接收我们的服务。</p>
     
  """,
                   //Optional parameters:
                   padding: EdgeInsets.all(8.0),
                   backgroundColor: Colors.white70,
                   defaultTextStyle: TextStyle(fontFamily: 'serif'),
                   linkStyle: const TextStyle(
                     color: Colors.redAccent,
                   ),
                   onLinkTap: (url) {
                     if(url=="https://h5.hhnry.com/agreement.html"){
                       NaviUtil.push(context, Agreement1("xiyi"));
//                      NaviUtil.push(new MaterialPageRoute(builder: (con){return
//                        Agreement1("xiyi");
//                      }));
                     }else{
                       NaviUtil.push(context, Agreement1("p"));

                     }
//                      launch(url);
                     // open url in a webview
                   },
                   onImageTap: (src) {
                     // Display the image in large form.
                   },
                   //Must have useRichText set to false for this to work.
                 ),
               ))
               ,
               Row(
                 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                 children: <Widget>[
                   InkWell(
                     child: Center(
                       child: Center(
                         child: Text(
                           "暂不使用",
                           style: TextStyle( fontSize: 18),
                         ),
                       ),
                     ),
                     onTap: (){
                       SystemChannels.platform.invokeMethod('SystemNavigator.pop');
                     },
                   )
                   ,
                   InkWell(
                     child: Center(
                       child: Text(
                         "同意",
                         style: TextStyle(color: Color(0xffFF5B00), fontSize: 18),
                       ),
                     ),
                     onTap: () {
                       NaviUtil.pop(context);

                       setFirst();
                     },
                   )
                 ],
               )

             ],
           ), onWillPop: (){
             SystemChannels.platform.invokeMethod('SystemNavigator.pop');
           })
           ,
           450);
     });
   }



    weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is WeChatAuthResponse) {

        setState(() {
          _result =
              "state :${res.state}   code:${res.code} success:${res.isSuccessful}";

          if (res.isSuccessful == true) {

            code = res.code;

            requestLogin();
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Image.asset(
                "assets/hpbg.png",
                fit: BoxFit.fill,
                width: MediaQuery.of(context).size.width,
              )),
              SizedBox(
                height: 50,
              ),
              InkWell(
                onTap: () async {


                  sendWeChatAuth(
                          scope: "snsapi_userinfo",
                          state: "wechat_sdk_demo_test")
                      .then((data) {
//                        Fluttertoast.showToast(msg: data.toString());
                  });
                },
                child: Container(
                  margin: EdgeInsets.only(left: 30, right: 30),
                  height: 50,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0xff00df6a),
                      borderRadius: BorderRadius.circular(10)),
                  child: Text(
                    "微信授权登录",
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white, fontSize: 19),
                  ),
                ),
              ),
              GestureDetector(
                child: Container(
                  margin:
                      EdgeInsets.only(left: 30, right: 30, top: 30, bottom: 60),
                  height: 50,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(color: Color(0xff959494))),
                  child: Text(
                    "手机号登录",
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Color(0xff959494), fontSize: 19),
                  ),
                ),
                onTap: () {
//                  fluwxUtil.shareOnlineVideoToSession("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
                  Navigator.pushAndRemoveUntil(context,
                      new MaterialPageRoute(builder: (BuildContext c) {
                    return new LoginWithPhone(false);
                  }), (r) => r == null);
                },
              ),
//              Row(
//
//                children: <Widget>[
//
//                  Checkbox(value: checked, onChanged: (v){
//                    this.checked =v;
//                  }),
//                  SizedBox(width: 10,),
//                  GestureDetector(child: Text("若勾选则表示您已同意《用户隐私协议》"),
//                  onTap: (){
//
//                    NaviUtil.push(context, new Agreement1(""));
//
//                  },
//                  )
//
//                ],
//
//              )
            ],
          ),
        ),
      ),
    );
  }

  List<String> list = List();

//登录
  void requestLogin() async {
     DialogUtil.showloadingdialog(context);

    try {
      Map<String, dynamic> map = Map<String, dynamic>();

      map["code"] = code;
      Map<String, dynamic> map1 = await HttpClient.requestOrderList(
          Config.requestApi + 'member/login/wechatLogin',
          data: map);

      _result = map1.toString();

      setState(() {});
      MemberInfoEntity memberInfoEntity = new MemberInfoEntity();
      memberInfoEntity = memberInfoEntityFromJson(memberInfoEntity, map1);
      DialogUtil.pop(context);
      if (memberInfoEntity.code == null) {
        return;
      }

      if (memberInfoEntity.code == 200) {
        SharedUtil.addStr(Constants.MEMBER_INFO, JsonUtil.map2json(map1));
        SharedUtil.addStr(Constants.LAST_LOGIN_TIME, DateTime.now().toString());
        Constants.memberInfoEntity = memberInfoEntity;
        Constants.TempMemberId = memberInfoEntity.data.memberId.toString();

        NaviUtil.pushAndRemove(context,
            HomePage(Constants.memberInfoEntity.data.memberId.toString()));
      }
    } catch (e) {
      DialogUtil.pop(context);
      print(e.toString());
    } finally {


      print(">>>>>finally111111");
    }
  }
  setFirst()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("first", false);
  }
}
